from pathlib import Path
from moviepy.editor import VideoFileClip
import os
import sys

from components.downloadVideo import download_video
from components.utils import extract_bv_and_p_from_url
import requests
import subprocess

# Add project root to path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if project_root not in sys.path:
    sys.path.append(project_root)


def check_folder(fp):
    """检查必要的文件夹是否存在"""
    if not os.path.exists(fp):
        os.makedirs(fp)

def video2audio(video_path, output_dir="bilibili_video"):
    try:
        audio_base_name = os.path.splitext(os.path.basename(video_path))[0]
        output_name = f"{audio_base_name}_audio"
        check_folder(output_dir)
        video = VideoFileClip(video_path)
        audio = video.audio
        audio_path = os.path.join(output_dir, f"{output_name}.mp3")
        audio.write_audiofile(audio_path)
        audio.close()
        video.close()
        return audio_path
    except Exception as e:
        return False

def stream_video(url: str, headers: dict = None, chunk_size: int = 8192):
    """
    流式读取视频内容
    
    Args:
        url (str): 视频URL
        headers (dict): 请求头
        chunk_size (int): 每次读取的字节数
        
    Yields:
        bytes: 视频数据块
    """
    try:
        with requests.get(url, headers=headers, stream=True) as response:
            response.raise_for_status()
            for chunk in response.iter_content(chunk_size=chunk_size):
                if chunk:
                    yield chunk
    except Exception as e:
        print(f"流式读取失败: {str(e)}")
        raise


def split_video_to_m4s(video_path: str, output_dir: str, segment_duration: int = 10):
    """
    将视频分割成m4s片段
    
    Args:
        video_path (str): 输入视频路径
        output_dir (str): 输出目录
        segment_duration (int): 每个片段的时长（秒）
    """
    try:
        # 创建输出目录
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        # 生成m4s片段
        cmd = [
            'ffmpeg',
            '-i', video_path,
            '-c:v', 'copy',  # 复制视频流，不重新编码
            '-c:a', 'copy',  # 复制音频流，不重新编码
            '-f', 'dash',    # 使用DASH格式
            '-seg_duration', str(segment_duration),  # 设置片段时长
            '-init_seg_name', 'init-$RepresentationID$.m4s',  # 初始化片段命名
            '-media_seg_name', 'chunk-$RepresentationID$-$Number%05d$.m4s',  # 媒体片段命名
            '-single_file', '0',  # 生成多个文件
            '-adaptation_sets', 'id=0,streams=v id=1,streams=a',  # 设置适配集
            f'{output_path}/manifest.mpd'  # MPD文件路径
        ]
        
        # 执行FFmpeg命令
        subprocess.run(cmd, check=True)
        
        return True
    except Exception as e:
        print(f"分割视频失败: {str(e)}")
        return False

def get_video_bitrate(video_path: str) -> int:
    """获取视频比特率（bits/second）"""
    try:
        cmd = [
            'ffprobe',
            '-v', 'error',
            '-select_streams', 'v:0',  # 选择第一个视频流
            '-show_entries', 'stream=bit_rate',
            '-of', 'default=noprint_wrappers=1:nokey=1',
            video_path
        ]
        result = subprocess.run(cmd, capture_output=True, text=True)
        bitrate = int(result.stdout.strip())
        return bitrate
    except Exception as e:
        print(f"获取视频比特率失败: {str(e)}")
        return 1024 * 1024 * 8  # 默认返回 1MB/s


if __name__ == "__main__":
    url = "https://www.bilibili.com/video/BV1wy4y1D7JT/?p=3"
    download_video(url)
